package cn.car.biz.carAccess.eventListener;

import cn.car.biz.carAccess.cache.VehicleLastPlateDetectCache;
import cn.car.biz.carAccess.cache.VehiclePlateResultCache;
import cn.car.biz.carAccess.event.PlateDetectResultEvent;
import cn.car.domains.ctx.PlateDetectedContext;
import cn.car.domains.entity.CameraInfoEntity;
import cn.car.domains.info.VehicleLastPlateDetectInfo;
import cn.car.utils.SemaphoreUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Slf4j
public class PlateDetectResultEventListenerVehicleSnapshot implements ApplicationListener<PlateDetectResultEvent> {

    @Resource
    private VehiclePlateResultCache vehiclePlateResultCache;

    @Resource
    private VehicleLastPlateDetectCache vehicleLastPlateDetectCache;



    @Override
    public void onApplicationEvent(PlateDetectResultEvent event) {
        PlateDetectedContext plateDetectedContext = event.getPlateDetectedContext();

        if (plateDetectedContext.getIsOpen() == null || !plateDetectedContext.getIsOpen()) {
            return;
        }


        vehiclePlateResultCache.put(event.getPlateDetectedContext().getCameraInfo().getIp(), plateDetectedContext);


        // 记录车辆最后一次识别信息
        CameraInfoEntity cameraInfoEntity = plateDetectedContext.getCameraInfoEntity();
        VehicleLastPlateDetectInfo vehicleLastPlateDetectInfo = new VehicleLastPlateDetectInfo(plateDetectedContext.getVehicleInfo().getPlateNumber(), new Date(), cameraInfoEntity.getEntryExitCode(), cameraInfoEntity.getRoadCode());
        vehicleLastPlateDetectCache.put(plateDetectedContext.getVehicleInfo().getPlateNumber(), vehicleLastPlateDetectInfo);


        SemaphoreUtil.release(plateDetectedContext.getCameraInfo().getIp());

    }

    @Override
    public boolean supportsAsyncExecution() {
        return true;
    }
}
